package com.woniuxy.Factory;

import com.woniuxy.intface.Person;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @Author：向天浩
 * @Date：2022/1/17 17:36
 * @Description :TODO
 */

public class BeanFactory {
    public Person getBean(String KeyName){
        Map<String,Person>map = new HashMap<String, Person>();
        //创建Properties
        Properties properties = new Properties();
        //当前工厂类去读取创建好的Properties配置文件
        InputStream resourceAsStream = BeanFactory.class.getResourceAsStream("Person.properties");
        try {
            //properties加载这个流
            properties.load(resourceAsStream);
            //获取key
            for (String key : properties.stringPropertyNames()) {
                //通过对应的key获取value
                String property = properties.getProperty(key);
                //获取到的value其实是类全名，那我们就可以通过反射创建对象。调用这个方法newInstance创建对象
                Person person = (Person)Class.forName(property).newInstance();
                //将properties的key和创建的对象当成参数放入map
                map.put(key,person);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        //返回对象
        return map.get(KeyName);
    }
}
